package com.appspot.yozmcup.oauth;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;

import com.appspot.yozmcup.DAO.YozmDAO;
import com.appspot.yozmcup.DO.User;
import com.appspot.yozmcup.util.UrlStore;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class OAuthCallback extends HttpServlet {
	private static final Logger log = Logger.getLogger(OAuthCallback.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		User user = null;

		HttpSession session = req.getSession();
		String oauthVerifier = req.getParameter("oauth_verifier");

		OAuthConsumer consumer = (DefaultOAuthConsumer) session.getAttribute("consumer");
		OAuthProvider provider = (DefaultOAuthProvider) session.getAttribute("provider");
		String token = null;
		String tokensecret = null;
		String redirectUrl = "";

		if (oauthVerifier != null) {
			try {
				provider.retrieveAccessToken(consumer, oauthVerifier.trim());
			} catch (Exception e) {
				e.printStackTrace();
			}

			token = consumer.getToken();
			tokensecret = consumer.getTokenSecret();
			session.setAttribute("consumer", consumer);
		}
		log.info("token:" + token + "::tokensecret:" + tokensecret);
		if (token != null && tokensecret != null) {
			String urlName = "";
			String sexCode = "";
			String nickname = "";
			boolean isYozmMember = YozmDAO.isYozmMember(consumer);
			log.info("isYozmMember:" + isYozmMember);
			if (isYozmMember) {
				JSONObject jsonResult = YozmDAO.getMyInfoObject(consumer);
				try {
					JSONObject jsonUser = jsonResult.getJSONObject("user");
					urlName = jsonUser.getString("url_name");
					sexCode = jsonUser.getString("sex_code");
					nickname = jsonUser.getString("nickname");
					user = new User(urlName, nickname, sexCode);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				redirectUrl = UrlStore.URL_MEMBER;
			} else {
				redirectUrl = UrlStore.URL_JOINYOZM;
			}

			session.setAttribute("user", user);
		} else {
			redirectUrl = UrlStore.URL_OAUTHREQUEST;
		}
		res.sendRedirect(redirectUrl);
	}
}
